//
//  CollectVM.swift
//  LeTu
//
//  Created by gy on 2023/12/25.
//

import Foundation

class CollectVM {
    
    /// 数据分页
    private var pageNum = 1
    /// 数据长度
    private(set) var pageSize = 20
    /// 关键词
    private var keyword: String?
    /// 收藏数据
    private(set) var sourceArr = [CollectModel]()
    
    // MARK: - 获取收藏列表
    func getCollects(isLoad: Bool, completeHandle: @escaping NetworkRequestHandle) {
        
        var pageNum = self.pageNum
        pageNum = isLoad ? pageNum + 1 : 1
        
        var param: [String : Any] = [String : Any]()
        param["page"] = pageNum
        param["pageSize"] = pageSize
        
        if let keyword = keyword {
            param["keyword"] = keyword
        }
        
        apiProvider.request(api: .getCollects(params: param)) { [weak self] json, jsonArr, code in
            MYLog("收藏列表信息：", json)
                        
            var dialog = DialogMessage()

            guard let strongSelf = self, let response = Mapper<ResponseModel>().map(JSON: json) else { return completeHandle(dialog) }
            dialog.code = response.code
            dialog.message = response.msg
            guard dialog.code == 200, let dataDic = response.data as? [[String: Any]] else { return completeHandle(dialog) }
            
            strongSelf.pageNum = pageNum
            let tempList = Mapper<CollectModel>().mapArray(JSONArray: dataDic)
            if isLoad {
                strongSelf.sourceArr = strongSelf.sourceArr + tempList
            } else {
                strongSelf.sourceArr = tempList
            }
            
            completeHandle(dialog)
            
        } failureHandler: { error in
            completeHandle(DialogMessage())
        }
        
    }
    
    // MARK: - 收藏｜取消收藏
    static func collectScenic(params: [String: Any], completeHandle: @escaping NetworkRequestHandle) {
        
        apiProvider.request(api: .collectScenic(params: params)) { json, jsonArr, code in
            MYLog("收藏｜取消收藏：",json)
            
            var dialog = DialogMessage()
            
            guard code == 200, let pm = Mapper<ResponseModel>().map(JSON: json) else { return completeHandle(dialog) }
            dialog.code = pm.code
            dialog.message = pm.msg
            completeHandle(dialog)
            
        } failureHandler: { error in
            completeHandle(DialogMessage())
        }
                
    }
    
    
}
